/*
 * @Author: xiaosihan 
 * @Date: 2024-09-20 08:21:22 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-20 22:38:39
 */


import userStore from "@views/userStore";
import { Button, Form, Input, Modal, Space } from "antd";
import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./updataPhone.module.less";
import updataPhoneSore from "./updataPhoneSore";
import loginApi from "@api/loginAPI";
import utils from "@utils";

interface Iprops {
    children?: ReactNode
}

type FieldType = {
    phone?: string;
    code?: string;
};

// 修改电话号码
export default function UpdataPhone() {

    const [form] = Form.useForm();
    const currentTime = useRef(0);
    const dom = useRef<HTMLDivElement | null>(null);
    const [open, setOpen] = useState(updataPhoneSore.open);
    const [step, setStep] = useState(updataPhoneSore.step);
    const [phone, setPhone] = useState(userStore.phone);
    const [time, setTime] = useState(0);
    useEffect(() => {

    }, []);

    useEffect(() => autorun(() => {
        setStep(updataPhoneSore.step);
        setOpen(updataPhoneSore.open);
        setPhone(userStore.phone);
    }), []);
    //发送短信验证码
    const send_sms = async () => {
        form.validateFields(["phone"])
            .then(async () => {
                const phone = form.getFieldValue("phone");
                const snedSMSResult = await loginApi.send_sms(phone, step + 1);
                setTime(utils.isDev ? 60 : 60);
            }).catch(err => {
            })

    }

    currentTime.current = time;
    // 自动倒计时
    if (currentTime.current > 0) {
        setTimeout(() => {
            setTime(currentTime.current - 1);
        }, 1000);
    }

    // 验证原来的手机号码
    const vrifyOright = () => {
        form.validateFields()
            .then(async () => {
                const phone = form.getFieldValue("phone");
                const code = form.getFieldValue("code");
                const error = await userStore.checkPhone(phone, code);
                if (error) {
                    form.setFields([{
                        name: ['code'],
                        errors: [error], // 清空错误  
                    }]);
                } else {
                    form.resetFields();
                    currentTime.current = 0;
                    setTime(0);
                    updataPhoneSore.setStep(2);
                }
            }).catch(err => {
            })
    }

    //验证新手机号码
    const vrify_new_phone = () => {
        form.validateFields()
            .then(async () => {
                const phone = form.getFieldValue("phone");
                const code = form.getFieldValue("code");
                const error = await userStore.updatePhone(phone, code);
                if (error) {
                    form.setFields([{
                        name: ['code'],
                        errors: [error], // 清空错误  
                    }]);
                } else {
                    form.resetFields();
                    currentTime.current = 0;
                    setTime(0);
                    updataPhoneSore.setOpen(false);
                }
            }).catch(err => {
            })
    }

    return (
        <Modal
            open={open}
            centered={true}
            footer={false}
            width={417}
            maskClosable={false}
            onCancel={() => {
                updataPhoneSore.setOpen(false);
            }}
        >
            <div
                ref={dom}
                className={styles.updataPhone}
            >
                <div className={styles.title} >修改手机号</div>
                <div className={styles.lable}> {step === 1 ? "请输入原手机号" : "请输入新手机号"} </div>
                <Form
                    form={form}
                    name="basic"
                    style={{ width: 315 }}
                    initialValues={{}}
                    onFinish={() => { }}
                    onFinishFailed={() => { }}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        name="phone"
                        rules={[{ required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]}
                    >
                        <Input
                            placeholder="请输入手机号"
                            size="large"
                            className={styles.input}
                        />
                    </Form.Item>

                    <div style={{ position: "relative" }} >
                        <Form.Item<FieldType>
                            name="code"
                            rules={[{ required: true, pattern: /^\d{6}$/, message: '请输入正确的验证码' }]}
                        >

                            <Input
                                size="large"
                                className={styles.input}
                                placeholder="请输入验证码"
                            />
                        </Form.Item>
                        <Button
                            className={styles.snedSMS}
                            size="large"
                            disabled={time > 0}
                            type="link"
                            onClick={() => send_sms()}
                        >发送验证码{time > 0 ? time : ""}</Button>
                    </div>
                </Form>
                <Button
                    type="primary"
                    block
                    className={styles.btn}
                    onClick={() => {
                        if (step === 1) {
                            vrifyOright();
                        } else if (step === 2) {
                            vrify_new_phone();
                        }
                    }}
                >
                    {step === 1 ? "下一步" : "完成"}
                </Button>
            </div>
        </Modal>
    );

}